import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routers'
import ViewUI from 'view-design'

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

/**
 * 路由前置拦截
 */
router.beforeEach((to, from, next) => {
  console.log(to.name)
  // 加载进度条
  ViewUI.LoadingBar.start();
  if(to.name === 'login' || to.name === '404'){
    next();
  }else{
    const token = localStorage.getItem("token");
    if(token){
      if(to.name === 'main'){
        // 跳转主页
        next({name: 'home'})
      }else{
        next()
      }
    }else{
      //用户未登录603
      errorHandle()
      next({ name: 'login' })
    }
  }

})

/**
 * 异常处理
 */
 const errorHandle = () => {
  ViewUI.Notice.error({
    title: "登陆超时，请重新登陆"
  })
}

/**
 * 路由后置拦截
 */
router.afterEach(route => {
  // 进度条加载完成
  ViewUI.LoadingBar.finish()
})

export default router
